var app = getApp();
const $ = require('../../utils/utils');
const config = require('../../config');
const user = require('../../manager/userManager.js')

Page({
    /**
     * 页面的初始数据
     */
    data: {
        footerConfig: {
            pagePersonal: true
        },
        user_img: "",
        user_nick_name: "未登录",
        user_credit_value: "0",
        total_borrow: "0",
        current_borrow: "0",
        rest_cash: "0",
        user_interger: "0",
        vipTime: "暂未开通会员",
        count: 0,
        creditCount: 0,
        showAuthor: false,
        version: '',
        phone: ''
    },


    /************ Life Cycle ************/

    onLoad: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        this.setData({
            version: app.globalData.appversion,
            phone: wx.getStorageSync('userPhone')
        })
        that.getUserInfo();
    },

    /************ Methods ***************/
    gotoAuthor: function () {
        let that = this
        wx.getSetting({
            success: (res) => {
                console.log('getSetting', res);
                if (res.authSetting['scope.userInfo'] == false || res.authSetting['scope.userLocation'] == false) {
                    wx.showModal({
                        title: '提示',
                        content: '需要您设置用户授权才能体验哦~',
                        showCancel: false,
                        confirmText: '去设置',
                        success: function (opt) {
                            wx.openSetting({
                                success: (res) => {
                                    that.getUserInfo();
                                }
                            });
                        }
                    });
                }
            },
        });

    },

    // 切换环境
    selServer: function () {
        var that = this;
        that.data.count++
        that.setData({
            count: that.data.count
        });
        if (that.data.count == 10) {
            wx.showActionSheet({
                itemList: ['生产服务器', '测试服务器', '开发服务器'],
                success: function (res) {
                    if (res.tapIndex == 0) {

                    } else if (res.tapIndex == 1) {
                        wx.setStorageSync('hostUrl', 'https://api.wdb007.com/wdb-wxapp-api-test/');
                        console.log(`路径${app.host_url}`);
                    }
                },
                fail: function (res) {
                    console.log(res.errMsg)
                }
            })
        }
    },

    bindSubmit: function (e) {
        user.saveMsgFormId(e.detail.formId)
    },

    /**************** 跳转相关 ***************/
    // 活动列表页面
    gotoActivity: function () {
        $.goto(config.page.activityList)
    },

    gotoGroupRank: function () {
        this.data.creditCount++
        this.setData({
            creditCount: this.data.creditCount
        })
        if (this.data.creditCount == 10) {
            wx.setStorageSync('toShareGroup', true)
            $.goto(config.page.groupRankList)
        }
    },

    gotoRank: function () {
        $.goto(config.page.weekRankList)
    },

    gotoInvite: function () {
        $.goto(config.page.invitePage)
    },

    toSelectBookPage: function () {
        $.goto(config.page.index, true)
    },

    payment: function (e) {
        $.goto(config.page.userWallet)
    },

    userRecord: function (e) {
        $.goto(config.page.userRecord)
    },

    toLoginPage: function () {
        // $.goto(config.page.login+'?path=test')
        $.goto(config.page.activityLottery)
    },

    helpCenter: function (e) {
        app.globalData.webview = {
            url: config.helpCenterUrl,
            title: '帮助中心'
        };
        $.goto(config.page.webview, false);
    },

    userCoupon: function () {
        let url = config.couponCenterUrl + "?userid=" + wx.getStorageSync("userid") + "&usertoken=" + wx.getStorageSync("usertoken");
        app.globalData.webview = {
            url: url,
            title: '我的优惠券'
        };
        console.log(url)
        $.goto(config.page.webview);
    },

    userRecord: function (e) {
        $.goto(config.page.userRecord)
    },

    vipCenter: function () {
        $.goto(config.page.vip)
    },

    borrowList: function (e) {//借阅历史
        $.goto(config.page.borrowList)
    },

    enter_wish_list: function () {
        $.goto(config.page.wishList)
    },

    makePhoneCall: function (e) {
        wx.makePhoneCall({
            phoneNumber: config.servicePhone
        });
    },

    // 借书架(心愿单) - 想看的书
    gotoCurrentReadList: function () {
        $.goto(config.page.borrowList + '?tab=0');
    },

    // 借书架(心愿单) - 看过的书
    gotoAlreadyReadList: function () {
        $.goto(config.page.borrowList + '?tab=1');
    },



    /********** 用户信息相关 *********/
    // 获取用户信息

    getUserInfo: function () {
        var that = this;
        wx.getUserInfo({
            success: function (res) {
                that.setData({
                    user_img: res.userInfo.avatarUrl,
                    user_nick_name: res.userInfo.nickName,
                    showAuthor: false
                })

                wx.setStorageSync('userinfo', res.userInfo);
                user.bindWXUserToUser()
                that.getCurrentUserInfo()
            },
            fail: function () {
                that.setData({
                    showAuthor: true
                })
                that.getCurrentUserInfo()
            }
        })
    },

    getCurrentUserInfo: function () {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask: true,
            success: function () {
                let data = {
                    userid: wx.getStorageSync('userid'),
                    usertoken: wx.getStorageSync('usertoken')
                }
                let url = $.getUrl(config.getUserInfo, data)
                $.get(url).then(data => {
                    wx.hideLoading();

                    console.log(data);
                    if (data.result == 1) {
                        user.saveLoginInfo(data.detail)
                        that.setData({
                            user_credit_value: data.detail.credit_value,
                            total_borrow: data.detail.borrowed_count,
                            current_borrow: data.detail.borrowing_count,
                            rest_cash: data.detail.cash_amount,
                            user_interger: data.detail.integration,
                        });

                        if (that.data.user_img.length < 1) {
                            that.setData({
                                user_img: data.detail.imgurl,
                                user_nick_name: data.detail.username,
                            })
                        }

                        wx.setStorageSync("cash_amount", data.detail.cash_amount)
                        wx.setStorageSync("borrowed_count", data.detail.borrowed_count)
                        wx.setStorageSync('VIP_Type', data.detail.vip_type)
                        that.setData({
                            vipTime: data.detail.vip_content
                        })

                        if (that.data.user_img == "") {
                            that.setData({
                                user_img: data.detail.imgurl
                            })
                        }

                        wx.setStorageSync('despoit_status', data.detail.status);
                        if (data.detail.usertoken != null) {
                            wx.setStorageSync('usertoken', data.detail.usertoken);
                            wx.setStorageSync('userid', data.detail.userid);
                            wx.setStorageSync('isLogin', true);
                        }
                        if (data.detail.deposit_amount == 99) {
                            wx.setStorageSync('deposit_flag', 1);
                        } else {
                            wx.setStorageSync('deposit_flag', 0);
                        }
                    } else {
                        $.showToast(data.message)
                    }
                }).catch(error => {
                    console.log("getCurrentInfo_()", error)
                })

            }
        })
    },
    // 发起活动邀请
    start_invite: function () {
        $.goto(config.page.activityList)
        // app.start_invite();
    },





    scanCode: function (e) {
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        console.log(e.detail.encryptedData)
        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
            app.scanCode();
        } else {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: '同意授权',
                success: function (res) {
                    console.log('getPhoneNumber', res)
                }
            })
        }

    },

})